<template>
  <div class="song-detail-container">
    <el-button
      class="back-btn"
      type="text"
      @click="goBack"
      :icon="ArrowLeft"
      style="margin-bottom: 16px"
    >
      返回
    </el-button>
    <div class="song-header">
      <el-image :src="songData.coverUrl" fit="cover" class="song-cover" />
      <div class="song-info">
        <h1 class="song-title">{{ songData.songName }}</h1>
        <div class="artist-info">
          <span class="artist-name">歌手：{{ songData.artistName }}</span>
          <el-button type="text" class="follow-btn" @click="toggleFollowArtist">
            {{ isFollowingArtist ? "已关注" : "关注" }}
          </el-button>
        </div>
        <div class="album-info">
          <span>所属专辑：{{ songData.albumName }}</span>
          <el-button type="text" class="collect-btn" @click="collectAlbum">
            {{ isAlbumCollected ? "已收藏专辑" : "收藏专辑" }}
          </el-button>
        </div>
        <div class="meta-info">
          <span>时长：{{ formatDuration(songData.duration) }}</span>
          <span>风格：{{ songData.genre }}</span>
          <span>语言：{{ songData.language }}</span>
        </div>
        <div class="actions">
          <el-button type="primary" :icon="VideoPlay" @click="playSong"
            >播放歌曲</el-button
          >
          <el-button :icon="Plus" @click="showAddToPlaylistDialog"
            >添加到歌单</el-button
          >
          <el-button :icon="Star" @click="toggleCollectSong">
            {{ isSongCollected ? "取消收藏" : "收藏歌曲" }}
          </el-button>
        </div>
      </div>
    </div>

    <div class="song-body">
      <el-tabs v-model="activeTab" class="song-tabs">
        <el-tab-pane label="歌词" name="lyrics">
          <div class="lyrics-container">
            <!-- 改进的歌词展示区域 -->
            <div class="lyrics-content-wrapper">
              <div class="lyrics-content" ref="lyricsContent">
                <template v-if="lyricsLines.length > 0">
                  <div
                    v-for="(line, index) in lyricsLines"
                    :key="index"
                    class="lyrics-line"
                    :class="{ active: index === activeLyricIndex }"
                  >
                    {{ line }}
                  </div>
                </template>
                <div v-else class="no-lyrics">
                  <el-icon><DocumentRemove /></el-icon>
                  <span>暂无歌词</span>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="评论" name="comments">
          <div class="comments-container">
            <div class="comment-input">
              <el-input
                v-model="newComment"
                placeholder="发表你的评论..."
                type="textarea"
                :rows="3"
              />
              <el-button
                type="primary"
                class="submit-comment"
                @click="submitComment"
              >
                发表评论
              </el-button>
            </div>
            <div class="comment-list">
              <div
                v-for="(comment, index) in comments"
                :key="index"
                class="comment-item"
              >
                <el-avatar :src="comment.avatar" size="small" />
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="comment-author">{{ comment.username }}</span>
                    <span class="comment-time">{{ comment.time }}</span>
                  </div>
                  <div class="comment-text">{{ comment.content }}</div>
                  <div class="comment-actions">
                    <el-button
                      type="text"
                      :icon="ChatDotRound"
                      @click="likeComment(comment.id)"
                    >
                      点赞({{ comment.likes }})
                    </el-button>
                    <el-button
                      type="text"
                      :icon="ChatDotRound"
                      @click="replyComment(comment)"
                    >
                      回复
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="详情" name="details">
          <div class="details-container">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="歌曲ID">{{
                songData.songId
              }}</el-descriptions-item>
              <el-descriptions-item label="比特率"
                >{{ songData.bitRate }} kbps</el-descriptions-item
              >
              <el-descriptions-item label="文件格式">{{
                songData.format
              }}</el-descriptions-item>
              <el-descriptions-item label="文件大小">
                {{ formatFileSize(songData.fileSize) }}
              </el-descriptions-item>
              <el-descriptions-item label="发行日期">{{
                songData.releaseDate
              }}</el-descriptions-item>
              <el-descriptions-item label="唱片公司">{{
                songData.recordCompany
              }}</el-descriptions-item>
              <el-descriptions-item label="标签">
                <el-tag
                  v-for="tag in songData.tags"
                  :key="tag"
                  type="info"
                  class="tag"
                >
                  {{ tag }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <div class="statistics">
              <h3>播放统计</h3>
              <div class="stats-grid">
                <div class="stat-item">
                  <div class="stat-value">
                    {{ formatNumber(songData.statistics?.playCount) }}
                  </div>
                  <div class="stat-label">播放次数</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">
                    {{ formatNumber(songData.statistics?.likeCount) }}
                  </div>
                  <div class="stat-label">点赞数</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">
                    {{ formatNumber(songData.statistics?.collectCount) }}
                  </div>
                  <div class="stat-label">收藏数</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">
                    {{ formatNumber(songData.statistics?.commentCount) }}
                  </div>
                  <div class="stat-label">评论数</div>
                </div>
                <div class="stat-item">
                  <div class="stat-value">
                    {{ formatNumber(songData.statistics?.shareCount) }}
                  </div>
                  <div class="stat-label">分享数</div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 添加到歌单对话框 -->
    <el-dialog v-model="playlistDialogVisible" title="添加到歌单" width="500px">
      <div class="playlist-dialog">
        <el-input
          v-model="playlistSearch"
          placeholder="搜索歌单"
          prefix-icon="Search"
          clearable
          class="search-input"
        />
        <div class="playlist-list">
          <div
            v-for="playlist in filteredPlaylists"
            :key="playlist.playlistId"
            class="playlist-item"
            @click="selectPlaylist(playlist)"
          >
            <el-image :src="playlist.coverUrl" class="playlist-cover" />
            <div class="playlist-info">
              <div class="playlist-name">{{ playlist.playlistName }}</div>
              <div class="playlist-meta">
                {{ playlist.songCount }}首歌曲 · {{ playlist.playCount }}次播放
              </div>
            </div>
            <el-icon
              v-if="selectedPlaylistId === playlist.playlistId"
              class="check-icon"
            >
              <Select />
            </el-icon>
          </div>
        </div>
        <div class="dialog-actions">
          <el-button @click="playlistDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="!selectedPlaylistId"
            @click="addToPlaylist"
          >
            添加到歌单
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ArrowLeft,
  ChatDotRound,
  DocumentRemove,
  Plus,
  Select,
  Star,
  VideoPlay,
} from "@element-plus/icons-vue";
import { computed, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import api from "../services/api";
const router = useRouter();
// 返回上一页
const goBack = () => {
  const from = route.query.from;
  if (from) {
    router.push(from);
  } else if (window.history.length > 1) {
    router.back();
  } else {
    router.push("/");
  }
};

const route = useRoute();
const songData = ref({});
const songLyrics = ref("");

// 修复 fetchSongDetail 方法，确保 songId 正确传递
const fetchSongDetail = async (songId) => {
  if (!songId) {
    console.error("songId 未定义，无法获取歌曲详情");
    return;
  }

  try {
    const res = await api.musicApi.getSongDetail(songId);
    console.log("获取歌曲详情成功:", res);
    if (res && res.code === 200 && res.data) {
      songData.value = {
        songId: res.data.songId,
        songName: res.data.songName,
        artistName: res.data.artistName,
        albumName: res.data.albumName,
        duration: res.data.duration,
        fileUrl: res.data.fileUrl,
        coverUrl: res.data.coverUrl,
        genre: res.data.genre,
        language: res.data.language,
        releaseDate: res.data.releaseDate,
        fileSize: res.data.fileSize,
        bitRate: res.data.bitRate,
        format: res.data.format,
      };
    } else {
      console.warn("后端返回数据不符合预期:", res);
      songData.value = {};
    }
  } catch (e) {
    if (e instanceof ApiError) {
      console.error(`API错误: ${e.code} - ${e.message}`);
    } else {
      console.error("未知错误:", e);
    }
    songData.value = {};
  }
};

// 修复 fetchSongLyrics 方法，确保 res.data 类型正确
const fetchSongLyrics = async (songId) => {
  if (!songId) {
    console.error("songId 未定义，无法获取歌词");
    return;
  }

  try {
    const res = await api.musicApi.getSongLyrics(songId);
    console.log("获取歌词成功:", res);
    if (!res || typeof res.data !== "string") {
      console.error("后端返回的歌词数据为空或类型不正确");
      songLyrics.value = [];
      return;
    }

    songLyrics.value = res.data.split("\n").map((line) => line.trim());
  } catch (e) {
    console.error("获取歌词失败:", e);
    songLyrics.value = [];
  }
};

onMounted(() => {
  const songId = route.params.id; // 修改为正确的路由参数名称
  if (songId) {
    fetchSongDetail(songId);
    fetchSongLyrics(songId);
  } else {
    console.error("路由参数中缺少 songId");
  }
});

const activeTab = ref("lyrics");
const isFollowingArtist = ref(false);
const isSongCollected = ref(false);
const isAlbumCollected = ref(false);
const playlistDialogVisible = ref(false);
const playlistSearch = ref("");
const selectedPlaylistId = ref(null);
const newComment = ref("");
const activeLyricIndex = ref(5); // 模拟当前播放到的歌词行

// 计算属性：过滤歌单
const filteredPlaylists = computed(() => {
  if (!playlistSearch.value) {
    return userPlaylists.value;
  }
  return userPlaylists.value.filter((playlist) =>
    playlist.playlistName
      .toLowerCase()
      .includes(playlistSearch.value.toLowerCase())
  );
});

// 计算属性：将歌词分割为行
const lyricsLines = computed(() => {
  if (!songLyrics.value) return [];
  return songLyrics.value.split("\n").filter((line) => line.trim() !== "");
});

// 方法：格式化时长
const formatDuration = (seconds) => {
  if (!seconds) return "00:00";
  const min = Math.floor(seconds / 60);
  const sec = seconds % 60;
  return `${min.toString().padStart(2, "0")}:${sec
    .toString()
    .padStart(2, "0")}`;
};

// 方法：格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// 方法：格式化数字
const formatNumber = (num) => {
  if (!num) return "0";
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + "M";
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + "K";
  }
  return num.toString();
};

// 方法：播放歌曲
const playSong = () => {
  console.log("播放歌曲:", songData.value.songName);
  // 实际项目中这里会调用播放API
};

// 方法：显示添加到歌单对话框
const showAddToPlaylistDialog = () => {
  playlistDialogVisible.value = true;
  selectedPlaylistId.value = null;
};

// 方法：选择歌单
const selectPlaylist = (playlist) => {
  selectedPlaylistId.value = playlist.playlistId;
};

// 方法：添加到歌单
const addToPlaylist = () => {
  if (!selectedPlaylistId.value) return;

  const playlist = userPlaylists.value.find(
    (p) => p.playlistId === selectedPlaylistId.value
  );
  console.log(`将歌曲添加到歌单: ${playlist.playlistName}`);

  // 实际项目中这里会调用添加到歌单API
  playlistDialogVisible.value = false;
  ElMessage.success(`已添加到 ${playlist.playlistName}`);
};

// 方法：收藏/取消收藏歌曲
const toggleCollectSong = () => {
  isSongCollected.value = !isSongCollected.value;
  ElMessage.success(isSongCollected.value ? "已收藏歌曲" : "已取消收藏");
};

// 方法：收藏专辑
const collectAlbum = () => {
  isAlbumCollected.value = !isAlbumCollected.value;
  ElMessage.success(isAlbumCollected.value ? "已收藏专辑" : "已取消收藏");
};

// 方法：关注/取消关注歌手
const toggleFollowArtist = () => {
  isFollowingArtist.value = !isFollowingArtist.value;
  ElMessage.success(isFollowingArtist.value ? "已关注歌手" : "已取消关注");
};

// 方法：提交评论
const submitComment = () => {
  if (!newComment.value.trim()) {
    ElMessage.warning("评论内容不能为空");
    return;
  }

  // 模拟添加新评论
  comments.value.unshift({
    id: comments.value.length + 1,
    username: "当前用户",
    avatar: "https://via.placeholder.com/40x40?text=Me",
    content: newComment.value,
    time: "刚刚",
    likes: 0,
  });

  newComment.value = "";
  ElMessage.success("评论发表成功");
};

// 方法：点赞评论
const likeComment = (commentId) => {
  const comment = comments.value.find((c) => c.id === commentId);
  if (comment) {
    comment.likes += 1;
    ElMessage.success("点赞成功");
  }
};

// 方法：回复评论
const replyComment = (comment) => {
  newComment.value = `回复 ${comment.username}: `;
  ElMessage.info("请在下方的评论框中输入回复内容");
};

onMounted(() => {
  // 模拟从API加载数据
  console.log("加载歌曲详情数据");
});
</script>

<style scoped>
.song-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.song-header {
  display: flex;
  margin-bottom: 30px;
}

.song-cover {
  width: 300px;
  height: 300px;
  border-radius: 8px;
  margin-right: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.song-info {
  flex: 1;
}

.song-title {
  font-size: 32px;
  margin: 0 0 15px 0;
  color: #333;
}

.artist-info,
.album-info {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  font-size: 16px;
}

.artist-name,
.album-info span {
  margin-right: 15px;
  color: #666;
}

.follow-btn,
.collect-btn {
  padding: 0;
  font-size: 14px;
}

.meta-info {
  display: flex;
  gap: 20px;
  margin: 20px 0;
  color: #888;
  font-size: 14px;
}

.actions {
  margin-top: 25px;
  display: flex;
  gap: 15px;
}

.song-tabs {
  margin-top: 20px;
}

/* 改进的歌词样式 */
.lyrics-container {
  padding: 0;
  background: linear-gradient(
    135deg,
    rgba(249, 249, 249, 0.9) 0%,
    rgba(245, 247, 250, 0.9) 100%
  );
  border-radius: 12px;
  min-height: 400px;
  max-height: 500px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
}

.lyrics-content-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 30px 20px;
}

.lyrics-content {
  text-align: center;
  width: 100%;
  max-width: 700px;
  padding: 30px 0;
}

.lyrics-line {
  font-size: 18px;
  line-height: 2.5;
  color: #666;
  margin: 5px 0;
  transition: all 0.3s ease;
  font-weight: 300;
  position: relative;
  opacity: 0.7;
}

.lyrics-line.active {
  font-size: 22px;
  font-weight: 600;
  color: #409eff;
  opacity: 1;
  transform: scale(1.05);
  text-shadow: 0 2px 10px rgba(64, 158, 255, 0.2);
}

.lyrics-line.active::before {
  content: "";
  position: absolute;
  left: -30px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  background-color: #409eff;
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    transform: translateY(-50%) scale(0.8);
    opacity: 0.7;
  }
  70% {
    transform: translateY(-50%) scale(1.2);
    opacity: 0.4;
  }
  100% {
    transform: translateY(-50%) scale(0.8);
    opacity: 0.7;
  }
}

.no-lyrics {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #999;
  font-size: 16px;
}

.no-lyrics .el-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

/* 其他样式保持不变 */
.comments-container {
  padding: 20px 0;
}

.comment-input {
  margin-bottom: 30px;
}

.submit-comment {
  margin-top: 10px;
  float: right;
}

.comment-item {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.comment-content {
  margin-left: 15px;
  flex: 1;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.comment-author {
  font-weight: bold;
  color: #333;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  margin-bottom: 10px;
  line-height: 1.5;
  color: #444;
}

.comment-actions {
  display: flex;
  gap: 15px;
}

.details-container {
  padding: 20px 0;
}

.tag {
  margin-right: 8px;
  margin-bottom: 5px;
}

.statistics {
  margin-top: 30px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 20px;
  margin-top: 15px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.playlist-dialog {
  padding: 10px;
}

.search-input {
  margin-bottom: 15px;
}

.playlist-list {
  max-height: 400px;
  overflow-y: auto;
}

.playlist-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
  position: relative;
}

.playlist-item:hover {
  background-color: #f5f7fa;
}

.playlist-cover {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 15px;
}

.playlist-info {
  flex: 1;
}

.playlist-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.playlist-meta {
  font-size: 12px;
  color: #888;
}

.check-icon {
  position: absolute;
  right: 15px;
  color: #409eff;
  font-size: 20px;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}
</style>
